package ru.spb.osll.myfit.server.handler;

import static org.junit.Assert.assertEquals;

import java.io.IOException;
import java.io.PrintStream;
import java.util.List;

import org.easymock.EasyMock;
import org.easymock.EasyMockSupport;
import org.easymock.IAnswer;
import org.junit.Before;
import org.junit.Test;

import ru.spb.osll.myfit.common.Page;
import ru.spb.osll.myfit.common.PageElement;
import ru.spb.osll.myfit.server.Converter;
import ru.spb.osll.myfit.server.ImportsPrinter;
import ru.spb.osll.myfit.server.parser.Constants;
import ru.spb.osll.myfit.server.parser.PageParser;
import ru.spb.osll.myfit.server.parser.RecursiveIncludeException;
import ru.spb.osll.myfit.util.CollectionUtils;
import ru.spb.osll.myfit.util.StringOutputStream;

public class WikiPageWriterTest extends EasyMockSupport{
  private PageParser m_parser;
  private ImportsPrinter importsPrinter;
  private WikiPageWriter m_pageWriter;
  @Before
  public void setUp() throws SecurityException, NoSuchMethodException {
    m_parser = new PageParser(new Converter());
    importsPrinter = createMock(ImportsPrinter.class);
    m_pageWriter = new WikiPageWriter(importsPrinter);
  }

  @Test
  public void testSavePage() throws IOException, RecursiveIncludeException {

    StringOutputStream buf = new StringOutputStream();
    PrintStream stream = new PrintStream(buf);
    List<PageElement> list = m_parser.parsePage(CollectionUtils
        .list("|set node regeneration submit delay|30 min|"));
    Page page = new Page();
    for (PageElement element : list) {
      page.insert(element);
    }

    importsPrinter.printImports(EasyMock.same(page),
        EasyMock.isA(PrintStream.class));
    EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
      @Override
      public Object answer() throws Throwable {
        PrintStream stream = (PrintStream) EasyMock.getCurrentArguments()[1];
        stream.append("!path fixtures.jar" + Constants.TABLE_SEPARATOR +
            "|Import|" + "\r\n" + "|ru.spb.osll.myfit.examples|" + "\r\n" +
            "\r\n");
        return null;
      }
    });

    replayAll();
    m_pageWriter.savePage(page, stream);
    verifyAll();

    String expected = "!path fixtures.jar" + Constants.TABLE_SEPARATOR +
        "|Import|" + "\r\n" + "|ru.spb.osll.myfit.examples|" + "\r\n" + "\r\n" +
        "|set node regeneration submit delay|30 min|" +
        Constants.TABLE_SEPARATOR;

    assertEquals(expected, buf.toString());

  }

}
